﻿@{
    ViewBag.Title = $"{GlobalContext.SystemConfig.SystemName} - Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@section header{
    <link href='@Url.Content("~/yisha/css/login.css")' rel="stylesheet" />
    <script>
        if (window.top !== window.self) { window.top.location = window.location };
    </script>
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/jquery.validation/1.14.0/jquery.validate.min.js"))

}
@model YiSha.Admin.Web.Areas.Models.LoginModel
<div class="login-panel">
    <div class="row section">
        <div class="col-sm-12">
            <form id="form">
                <h4 class="no-margin">Login @GlobalContext.SystemConfig.SystemName</h4>
                <br />


                <button class="btn btn-success btn-block" onclick="loginByGoogle(); return false;">Login With Google Account</button>

                <br />


                @*<button class="btn btn-success btn-block" onclick="loginByOffice(); return false;">Login With Office Account</button>*@
                <input id="officeLogin" type="button" value="Login With Office Account" class="btn btn-success btn-block" />
            </form>
        </div>
    </div>
    <div class="login-footer">
        @*<div style="text-align:center">
                &copy; 2018-@DateTime.Now.Year <a href="#" target="_blank" style="color:white"></a> All Rights Reserved.<br>
                <a href="http://www.beian.miit.gov.cn/" target="_blank" rel="nofollow"></a><br>
            </div>*@
    </div>
</div>
<div style="display:none;">  <div class="g-signin2" id="btnLoginByGoogle"></div></div>
<script type="text/javascript">
    $(function () {

        if ($.cookie('RememberMe') == 1) {
            $("#rememberMe").prop("checked", true);
            if ("@GlobalContext.SystemConfig.LoginProvider" == "Cookie") {
                if (!ys.isNullOrEmpty($.cookie('UserToken'))) {
                    redirectToIndex();
                }
            }
            else {
                $.removeCookie("UserToken", { path: '/' });
            }
        }
        $("#rememberMe").click(function () {
            if ($(this).prop("checked")) {
                $.cookie('RememberMe', 1, { expires: 30, path: '/' });
            }
        });

        $("#imgCaptchaCode").click(function () {
            $(this).attr("src", '@Url.Content("~/Home/GetCaptchaImage")' + '?t=' + new Date().getTime());
        });

        $("#form").validate({
            rules: {
                userName: { required: true },
                password: { required: true }
            }
        });

        $.validator.setDefaults({
            submitHandler: function () {
                loginForm();
            }
        });

        clearOldUser();

        var $connect = $("#officeLogin");
        var officeAuthUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=" + "@Model.OfficeClientID" + "&response_type=code&redirect_uri=" + "@Model.OfficeRedirectUrl" + "&response_mode=query&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2FUser.read&state=12345&prompt=select_account";
        
        $connect.click(function () {
            win = window.open(officeAuthUrl, 'officeAuthUrl', 'width=972,height=660,modal=yes,alwaysRaised=yes');
        });

    });

    function loginForm() {
        if ($("#form").validate().form()) {
            var postData = $("#form").getWebControls();
            ys.ajax({
                url: '@Url.Content("~/Home/LoginJson")',
                type: "post",
                data: postData,
                success: function (obj) {
                    if (obj.Tag == 1) {
                        ys.msgSuccess(obj.Message);
                        redirectToIndex();
                    }
                    else {
                        ys.msgError(obj.Message);
                    }
                }
            });
        }
    }

    function redirectToIndex() {
        location.href = '@Url.Content("~/Home/Index")';
    }

    function loginByGoogle() {
         location.href = '@Url.Content("~/OAuth/GoogleLogin")';
    }

    function loginByOffice() {
        var url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=0e75d306-172c-4e09-bcc5-90d817be3e74&response_type=code&redirect_uri=http%3a%2f%2flocalhost%3a5000%2fOAuth%2fOfficeLoginCallback&response_mode=query&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2FUser.read&state=12345&";
        window.open(url);
        //window.open(url, 'popUpWindow', 'height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
    }

    function clearOldUser() {
        //只有这样，才能达到切换账号的效果，否则一个google账号，你永远也无法切换测试了
        var watchTimer = setInterval(function () {
            if (typeof gapi === "undefined") return;
            if (typeof gapi.auth2 === "undefined") return;
            if (typeof gapi.auth2.getAuthInstance === "undefined") return;
            {
                clearInterval(watchTimer);
                setTimeout(() => {
                    var auth2 = gapi.auth2.getAuthInstance();
                    auth2.signOut().then(function () {
                        console.log('clearOldUser User signed out.');
                        auth2.disconnect();
                    });
                    auth2.disconnect();
                },2000);
            }
        }, 500);
    }
</script>